package com.dingpeikeji.quickdeer.modules.rentproduct.web;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.modules.payinfo.entity.TPayinfo;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductSettleService;

/**
 * 用户结算
 */
@Controller
@RequestMapping(value = "${adminPath}/rentproduct/settle")
public class PentproductSettleController {
	@Autowired
	private RentproductSettleService rentproductSettleService;
	/**
	 * 支付信息列表
	 * @return
	 */
	@RequiresPermissions("rentproduct:settle:view")
	@RequestMapping("list")
	public String list(TPayinfo payinfo, HttpServletRequest request, HttpServletResponse response, Model model){
		// 如果日期范围有空，则采用默认日期范围，即当天前一个月
		if(StringUtils.isEmpty(payinfo.getCreateDateStart()) ||
				StringUtils.isEmpty(payinfo.getCreateDateEnd())) {
			Calendar calendar = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			payinfo.setCreateDateEnd(sdf.format(calendar.getTime()));
			calendar.add(Calendar.MONTH, -1);
			payinfo.setCreateDateStart(sdf.format(calendar.getTime()));
		}
		model.addAttribute("payinfo", payinfo);
		model.addAttribute("page", rentproductSettleService.findPage(new Page<TPayinfo>(request,response), payinfo));
		return "modules/rentproduct/settleList";
	}
	
	/**
	 * 到账
	 * @return
	 */
	@RequiresPermissions("rentproduct:settle:edit")
	@RequestMapping("receive")
	public String receive(TPayinfo payinfo, RedirectAttributes redirectAttributes) {
		try {
			rentproductSettleService.settle(payinfo);
			redirectAttributes.addFlashAttribute("message", "结算成功");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", "结算失败");
		}
		return "redirect:"+Global.getAdminPath()+"/rentproduct/settle/list/?repage";
	}
	
}
